from substrateinterface import SubstrateInterface, Keypair
from substrateinterface.exceptions import SubstrateRequestException
import json

def put(key,value):

    substrate = SubstrateInterface(
        url="ws://127.0.0.1:9944",
        ss58_format=42,
        type_registry_preset='substrate-node-template'

    )

    #keypair = Keypair.create_from_mnemonic('episode together nose spoon dose oil faculty zoo ankle evoke admit walnut')
    keypair = Keypair.create_from_uri('//Alice')

    call = substrate.compose_call(
        call_module='SimpleEvent',
        call_function='do_map',
        call_params={
            'key': key,
            #'value': [json.dumps(value)]
            'value': value
        }
    )

    extrinsic = substrate.create_signed_extrinsic(call=call, keypair=keypair)

    try:
        receipt = substrate.submit_extrinsic(extrinsic, wait_for_inclusion=True)
        print("Extrinsic '{}' sent and included in block '{}'".format(receipt.extrinsic_hash, receipt.block_hash))
        return {
            "code":200,
            "extrinsic_hash":receipt.extrinsic_hash,
            "block_hash":receipt.block_hash
        }
    except SubstrateRequestException as e:
        print("Failed to send: {}".format(e))
        return {
            "code":201,
            "extrinsic_hash":'',
            "block_hash":''
        }
